<template>
  <div class="map">
    <div class="flex-column" v-bind:style='echartRightClickStyle'>
      <el-button @click="returnLast">返回上层</el-button><br>
      <el-button @click="returnTop">返回顶层</el-button>
    </div>
    <EchartTemp id="covid19Map" :width="mapWidth" :height="mapHeight" :echartRightClickFlag="true" :echartRightClick="echartRightClick" :echartClick="echartClick" :options="options"></EchartTemp>
  </div>
</template>

<script>
import { getMapData } from '@/api/covid19Api'
import EchartTemp from '@/common/echartTemp.vue'
import axios from 'axios'
import nameMap from '@/utils/enToZhForMap'
import getJsonName from '@/utils/mapJsonName'

export default {
  name: "MapComponent",
  props: {
    curAddress: {
      type: Object,
      default: ()=>({id:0}),
    }
  },
  data() {
    return {
      mapWidth: "80%",
      mapHeight: "60vh",
      getMapDataParams: {},
      options: {},
      mapTimeoutId: [],
      echartRightClickStyle: {display:"none",position:"absolute","z-index":"99999"},
      echartRightClick: (params) => {
        let that = this
        let tmp = Object.assign({},that.echartRightClickStyle)
        tmp.display = "block"
        tmp.top = params?.event?.offsetY + "px"
        tmp.left = params?.event?.offsetX + "px"
        that.echartRightClickStyle = tmp
        // 清除之前的定时任务
        for (let id in that.mapTimeoutId) {
          clearTimeout(that.mapTimeoutId[id])
        }
        let a =setTimeout(function() { that.echartRightClickStyle.display="none" }, 2000);
        that.mapTimeoutId.push(a)
      },
      echartClick: (params) => {
        if (getJsonName(params?.data?.addressName) == "") {
            this.$message.error('当前不支持查看此区域信息哦~')
            return
        }
        // 保存当前地图至上级地图
        this.$lastMapConf.id = this.$mapConf.id
        this.$lastMapConf.name = this.$mapConf.name
        // 将点击的地图信息保存至当前地图 并刷新路由
        this.$mapConf.id = params?.data?.id
        this.$mapConf.name = params?.data?.addressName
        this.refresh()
      }
    }
  },
  watch: {
    curAddress: {
      handler(val) {
        this.getMapDataParams.id = val?.id;
      },
      deep: true,
      immediate: true, // 初次监听即执行
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      getMapData(this.getMapDataParams).then(res => {
        let data = res.data
        for (let key in data) {
          let value = data[key]
          data[key].name = value?.addressName
          data[key].value = value?.totalConfirm - value?.totalDead - value?.totalHeal
        }
        this.drawMap(data)
      }).catch(err => {
        console.log(err);
      });

    },
    drawMap(data) {
      let that = this
      // 是否显示label
      let labelShow = true
      let jsonFile = '/mapJson/world.json'
      if (that.getMapDataParams.id == 0) {
        jsonFile = '/mapJson/world.json'
        labelShow = false
      } else {
        jsonFile = '/mapJson/'+getJsonName(that.$mapConf?.name)+'.json'
      }

      let valueMap = data.map(item => {return item.value})

      valueMap.sort(function(a,b){return a-b})
      let mNum = valueMap[Math.floor(valueMap.length / 2)]
      let resMax = mNum > 50 ? mNum : 50

      axios.get(jsonFile).then(function (geoJson) {
        that.$echarts.registerMap('map', geoJson?.data);
        that.options = {
          layoutCenter: ['50%', '50%'],
          tooltip: {
            trigger: 'item',
            formatter: (params) => {
              let html = ""
              html += `<div>
                        <span>${params?.name}</span>
                      </div>
                      <div>
                        <span style="display:inline-block;border-radius:5px;margin-right:5px;width:10px;height:10px;background-color:${params?.color};"></span>
                        <span>现存确诊人数：${params?.data?.value}</span>
                      </div>
                      <div>
                        <span style="display:inline-block;border-radius:5px;margin-right:5px;width:10px;height:10px;background-color:${params?.color};"></span>
                        <span>累计确诊人数：${params?.data?.totalConfirm}</span>
                      </div>
                      <div>
                        <span style="display:inline-block;border-radius:5px;margin-right:5px;width:10px;height:10px;background-color:${params?.color};"></span>
                        <span>累计死亡人数：${params?.data?.totalDead}</span>
                      </div>
                      <div>
                        <span style="display:inline-block;border-radius:5px;margin-right:5px;width:10px;height:10px;background-color:${params?.color};"></span>
                        <span>累计治愈人数：${params?.data?.totalHeal}</span>
                      </div>`
              return html
            }
          },
          visualMap: [{
            type: "piecewise",
            splitNumber: 1,
            orient: 'vertical',
            left: 'right',
            top: '100px',
            pieces:[{value: 0, color: 'green'}]
          },{
            min: 0,
            max: resMax,
            text: ['High', 'Low'],
            realtime: false,
            calculable: true,
            orient: 'vertical',
            left: 'right',
            top: 'center',
            inRange: {
              color: ['lightskyblue', 'yellow', 'orangered']
            }
          }],
          series: [
            {
              name: '世界疫情地图',
              type: 'map',
              map: 'map',
              label: {
                show: labelShow,
                formatter: function(params){
                  if (params?.value == 0) {
                    return `{a|${params?.name}}`
                  }
                },
                rich: {
                  a: {
                    color: "#67C23A"
                  }
                }
              },
              data: data,
              // 自定义名称映射
              nameMap: nameMap
            }
          ],
        }

      });
    },
    refresh () {
      this.$router.replace({
        path: '/refresh',
        query: {
          t: Date.now()
        }
      })
    },
    returnTop () {
      // 更新上级地图
      this.$lastMapConf.id = 0
      this.$lastMapConf.name = ""
      // 更新当前地图
      this.$mapConf.id = 0
      this.$mapConf.name = ""
      this.refresh()
    },
    returnLast () {
      // 设置当前地图为上级地图
      this.$mapConf.id = this.$lastMapConf.id
      this.$mapConf.name = this.$lastMapConf.name
      // 设置上级地图为顶级
      this.$lastMapConf.id = 0
      this.$lastMapConf.name = ""

      this.refresh()
    }
  },
  components: { EchartTemp }
}
</script>
<style scoped lang="scss">

</style>
